package hn.cch.web.sse.schedule;

import hn.cch.web.sse.controller.SseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@Component
public class SseSchedule {

    private static final Logger logger = LoggerFactory.getLogger(SseSchedule.class);

    /**
     * 定时检查SSE客户端是否关闭
     */
    @Scheduled(fixedDelay = 1000)
    public void checkSseEmitter() {
        SseController.sseEmitterMap.forEach((uid, sseEmitter) -> {
            try {
                sseEmitter.send(SseEmitter.event().reconnectTime(1000L));
                logger.info("check {} send success", uid);
            } catch (IOException e) {
                logger.info("send error:{}", e.getMessage());
                sseEmitter.complete();
                SseController.sseEmitterMap.remove(uid);
            }
        });
    }

}
